package com.woniuxy.boot.nb_auth.controller.app;

import cn.hutool.jwt.JWTUtil;
import com.woniuxy.boot.common.dto.UserDTO;
import com.woniuxy.boot.common.pojo.ResponseResult;
import com.woniuxy.boot.common.vo.UserLoginVO;
import com.woniuxy.boot.nb_auth.bean.User;
import com.woniuxy.boot.nb_auth.service.UserService;
import com.woniuxy.boot.nb_auth.util.SmsUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("app/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsUtil smsUtil;

    @Value("${jwt.secretKey}")
    private String secretKey;

    @GetMapping("test")
    public ResponseResult<Void> test() {
        System.out.println("成功");
        return ResponseResult.SUCCESS;
    }

    /**
     * 根据手机号码获取验证码
     * 参数:手机号
     **/
    @GetMapping("getCaptcha")
    public ResponseResult<Void> getCaptcha(@RequestParam("phone") String phone) {
        Integer code = 1000 + (int) (Math.random() * 9000);
        try {
            redisTemplate.opsForValue().set(phone, code.toString(), 5, TimeUnit.MINUTES);
            System.out.println(code);
            smsUtil.Send(code, phone);
            return ResponseResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.FAIL;
        }
    }

    /**
     * 根据手机号码登录账号 参数:UserLoginVO（电话号码,验证码）
     **/
    @PostMapping("loginByPhone")
    public ResponseResult<Void> loginByPhone(@RequestBody UserLoginVO userLoginVO, HttpServletResponse response) {
        try {
            //根据用户的电话去redis拿验证码
            String code = redisTemplate.opsForValue().get(userLoginVO.getPhone());
            if (code != null) {
                //如果用户输入验证码和redis的对上,成功登录,返回token
                if (userLoginVO.getCaptcha().equals(code)) {
                    User user = userService.getUserByPhone(userLoginVO.getPhone());
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", String.valueOf(user.getId()));
                    String token = JWTUtil.createToken(map, secretKey.getBytes());
                    response.setHeader("token", token);
                    return ResponseResult.SUCCESS;
                }
                //如果用户输入验证码和redis的没对上,登录失败,返回响应验证码不正确
                return new ResponseResult<>(701, "验证码错误");
            }
            return new ResponseResult<>(702, "验证码无效");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("未知异常");
        }
    }

    /**
     * 根据用户id获取该用户绑定的车辆数量
     * @param id 用户id
     * @return
     */
    @GetMapping("getUserById")
    public UserDTO getUserById(@RequestParam("id") Long id) {
        User user = userService.getUserById(id);
        UserDTO userDTO=new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        System.out.println("用户数据:{"+userDTO+"}");
        return userDTO;
    }

    /**
     * 用户的车辆绑定数量+1
     * @param id 用户id
     */
    @GetMapping("carNumPlusOne")
    public void carNumPlusOne(@RequestParam("id") Long id) {
        userService.carNumPlusOne(id);
    }

    /**
     * 用户的保单数量+1
     * 用户状态修改为已购买保险
     * @param id 用户id
     */
    @GetMapping("policyNumPlusOne")
    public void policyNumPlusOne(@RequestParam("id") Long id) {
        userService.policyNumPlusOne(id);
    }


}

